﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class manager_services_EditTemplate : CMSManagementPageBase
{
    private string method;
    private Dictionary<string, string> arguments = new Dictionary<string, string>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.RequestType.ToLower() == "get")
        {
            if (Request.QueryString["method"] != null)
                method = Request.QueryString["method"];

            foreach (string item in Request.QueryString.AllKeys)
            {
                if (item != "method")
                    arguments.Add(item, Request.QueryString[item]);
            }
        } else if (Request.RequestType.ToLower() == "post")
        {
            if (Request.Form["method"] != null)
                method = Request.Form["method"];

            foreach (string item in Request.Form.AllKeys)
            {
                if (item != "method")
                    arguments.Add(item, Request.Form[item]);
            }
        }

        Response.Clear();
        switch (method)
        {
            case "GetTemplate":
                GetTemplate();
                break;
            case "GetTemplates":
                GetTemplates();
                break;
            case "SaveTemplate":
                SaveTemplate();
                break;
            case "CreateTemplate":
                CreateTemplate();
                break;
        }

    }

    private void SaveTemplate()
    {
        string template = arguments["t"];
        template = Server.HtmlDecode(template);

        string templatePath = Server.MapPath(Path.Combine(mWebsite.TemplatesFolder, arguments["tname"]));

        bool temp = arguments.ContainsKey("temp");
        if (temp)
            templatePath += @"\template_temp.xsl";
        else
            templatePath += @"\template.xsl";

        FileStream fs = new FileStream(templatePath, FileMode.Create, FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);

        w.Write(template);

        w.Close();
        fs.Close();
        w.Dispose();
        fs.Dispose();
    }

    private void GetTemplate()
    {
        if (!arguments.ContainsKey("tname"))
        {
            Response.StatusCode = 300;
            Response.StatusDescription = "Required parameter tpath not supplied";
            return;
        }
        string templatePath = Server.MapPath(Path.Combine(mWebsite.TemplatesFolder, arguments["tname"]));

        if (arguments.ContainsKey("temp"))
            templatePath += @"\template_temp.xsl";
        else
            templatePath += @"\template.xsl";

        FileStream fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read);
        StreamReader r = new StreamReader(fs);

        Response.Write(r.ReadToEnd());
        r.Close();
        fs.Close();
        r.Dispose();
        fs.Dispose();
    }

    private void CreateTemplate()
    {
        if (!arguments.ContainsKey("tname"))
        {
            Response.Write("no");
            return;
        }
        string tname = arguments["tname"];

        DirectoryInfo dir = new DirectoryInfo(Server.MapPath(Path.Combine(mWebsite.TemplatesFolder, tname)));

        // create the template folder if it doesn't exist
        if (!dir.Exists)
            dir.Create();

        // copy the default template into a brand new template file
        FileStream fsSource = null, fsDest = null;
        StreamReader r = null;
        StreamWriter w = null;
        try
        {
            fsSource = new FileStream(Server.MapPath(Request.ApplicationPath.TrimEnd('/') + "/xsl/defaultTemplate.xsl"), FileMode.Open);
            fsDest = new FileStream(Path.Combine(dir.FullName, "template.xsl"), FileMode.CreateNew);

            r = new StreamReader(fsSource);
            w = new StreamWriter(fsDest);

            w.Write(r.ReadToEnd());

            w.Close();
            r.Close();

            Response.Write(string.Format("{0}", tname));
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message+"<br/>"+ex.StackTrace);
            return;
        }
        finally
        {
            if (fsSource != null) { fsSource.Close(); }
            if (fsDest != null) { fsDest.Close(); }
            if (w != null) { w.Close(); }
            if (r != null) { w.Close(); }
        }
    }

    private void GetTemplates()
    {
        // and the xslt template list if applicable
        DirectoryInfo dir = new DirectoryInfo(System.Web.Hosting.HostingEnvironment.MapPath(mWebsite.TemplatesFolder));
        if (dir.Exists)
        {
            DirectoryInfo[] xslTemplates = new DirectoryInfo[0];
            xslTemplates = dir.GetDirectories();

            foreach (DirectoryInfo xslTemplate in xslTemplates)
            {
                if (File.Exists(Path.Combine(xslTemplate.FullName, "template.xsl")))
                    Response.Write(string.Format("#{0}", xslTemplate.Name));
            }
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        //base.Render(writer);
        
    }
}
